package mail.folder;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.mail.Folder;

import mail.db.DataBase;
import mail.owner.Owner;

public class MailFolder {
	public static final String TABLE = "folders";
	public static final String ID = "id";
	public static final String OWNER = "owner";
	public static final String NAME = "name";
	public static final String PARENT = "parent";
	
	private DataBase db;
	
	private int id;
	private Owner owner;
	private String name;
	private MailFolder parent;
	
	public MailFolder(int id) throws SQLException {
		this(id, DataBase.getInstance());
	}
	
	private MailFolder(int id, DataBase db) throws SQLException {
		this.id = id;
		this.db = db;
		String query = "SELECT * FROM "+TABLE+" WHERE "+ID+"="+id+" LIMIT 1";
		ResultSet rs = db.executeQuery(query);
		rs.first();
		this.owner = new Owner(rs.getInt(OWNER));
		this.name = rs.getString(NAME);		
		this.parent = (id != rs.getInt(PARENT)) ? new MailFolder(rs.getInt(PARENT)) : null;
	}
	
	public MailFolder(Owner owner, Folder folder, MailFolder parent) throws SQLException {
		this(owner, folder.getName(), parent);
	}
	
	public MailFolder(Owner owner, String name) throws SQLException {
		this(owner, name, null);
	}
	
	public MailFolder(Owner owner, String name, MailFolder parent) throws SQLException {
		this(owner, name, parent, DataBase.getInstance());
	}
	
	private MailFolder(Owner owner, String name, MailFolder parent, DataBase db) throws SQLException {
		this.owner = owner;
		this.name = name;
		this.parent = parent;
		this.db = db;
		
		String query;
		try {
			System.out.println("Searching for folder ("+name+")");
			query = "SELECT * FROM "+TABLE+" WHERE ("+OWNER+"="+owner.getID()+" AND "+NAME+"=\""+name+"\")";
			ResultSet rs = db.executeQuery(query);
			rs.first();
			id = rs.getInt(ID);
			System.out.println("Found folder ("+name+") @ id = "+id);
		} catch (SQLException e) {
			System.out.println("Could not find folder ("+name+") in database. Adding it.");
			int parentID = (parent != null) ? parent.getID() : 0;
			query = "INSERT INTO "+TABLE+" ("+OWNER+","+NAME+","+PARENT+") VALUES ("+owner.getID()+",\""+name+"\","+parentID+")";
			id = db.executeUpdate(query);
			
			if (parent == null) {
				System.out.println("Setting ROOT's parent to itself");
				query = "UPDATE "+TABLE+" SET "+PARENT+"="+id+" WHERE "+ID+"="+id;
				db.executeUpdate(query);
			}
		}
	}
	
	public int getID() { return id; }
	public Owner getOwner() { return owner; }
	public String getName() { return name; }
	public boolean hasParent() { return parent != null; }
	public MailFolder getParent() { return parent; }
}
